package com.chenl.provider.DEMOS.上传文件到Resources下;

import com.chenl.provider.DTO.vo.Result;
import com.chenl.provider.util.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {
    @Autowired
    FileUtils fileUtils;

    @GetMapping("/test")
    public Result<Object> testReslover(MultipartFile file) throws Exception{
        File file1 = getUploadPath("/static/images");
//        ioUtils.outPutByMultFile(file,"/image"+"/abc.txt");
        //7fdbb89debe44eb58c9d0f65f1caf794
        //610c574095c143c5bb2bac29c2220c82
        return new Result<>();
    }

    @GetMapping("/test2")
    public Result<Object> testReslover2(MultipartFile file) throws Exception{
        ApplicationHome applicationHome=new ApplicationHome(this.getClass());
        String pathStr = applicationHome.getDir().getParentFile().getParentFile().getAbsolutePath()+"/src/main/resources";
        String s = FileUtils.readTxtFile(pathStr+"/image"+"/abc.txt");
        System.out.println(s);
        return new Result<>(s);
    }

    /**
     * 获取项目路径下的文件,若不存在则创建
     *
     * @return 文件
     */
    public static File getUploadPath(String relativePath) {
        try {
            File path = new File(ResourceUtils.getURL("resources:").getPath());
            if (!path.exists()) {
                path = new File("");
            }
            File upload = new File(path.getAbsolutePath(), relativePath);
            if (!upload.exists()) {
                boolean r = upload.mkdirs();
                if (!r) {
                    log.info("创建临时路径失败。。。");
                    return null;
                }
            }
            return upload;
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}
